package com.leyou.upload.service.impl;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.leyou.upload.service.UploadService;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class UploadServiceImpl implements UploadService {
    //引入日志
    private static final Logger logger =  LoggerFactory.getLogger(UploadServiceImpl.class);

    //支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg");



    @Autowired
    FastFileStorageClient storageClient;

    @Override
    public String uploadImage(MultipartFile file) {
        try {
            //校验文件类型
            String type = file.getContentType();
            if (!suffixes.contains(type)){
                logger.info("文件类型不支持:{}",type);
            }
            //校验图片内容
            BufferedImage image = ImageIO.read(file.getInputStream());
            if (image == null){
                logger.info("图片内容不合格");
            }
            //保存图片
            String originalFilename = file.getOriginalFilename();
            String ext = StringUtils.substringAfterLast(originalFilename, ".");

            //上传文件 需要参数,输入流,文件大小,文件后缀

            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            return "http://image.leyou.com/"+storePath.getFullPath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
